﻿#include "ListNode.h"


Listnode* LTcreatone(ListData x)
{
	Listnode* pcur= malloc(sizeof(Listnode));
	if (pcur== NULL)
	{
		perror("malloc erro");
		exit(1);
	}
	pcur->x = x;
	pcur->next = pcur->prev = pcur;
	return pcur;

}

Listnode* LTinit()
{
	Listnode* phead = LTcreatone(-1);
	return phead; 

}

void LTprint(Listnode* phead)
{
	assert(phead);
	Listnode* pcur = phead->next;
	while (pcur != phead)
	{
		printf("%d->", pcur->x);
		pcur = pcur->next;
	}
	printf("\n");
}

void LTpushBack(Listnode* phead, ListData x)
{
	assert(phead);

	Listnode* newnode = LTcreatone(x);
	newnode->next = phead;
	newnode->prev = phead->prev;
	phead->prev->next = newnode;
	phead->prev = newnode;
}

void LTpushFront(Listnode* phead, ListData x)
{
	assert(phead);

	Listnode* newnode = LTcreatone(x);
	newnode->next = phead->next;
	newnode->prev = phead;
	phead->next->prev = newnode;
	phead->next = newnode;
}


void LTpopBack(Listnode* phead)
{
	assert(phead && (phead->next != phead));
	Listnode* del = phead->prev;
	del->prev->next = phead;
	phead->prev = del->prev;
	free(del);
	del = NULL;
}

void LTpopFront(Listnode* phead)
{
	assert(phead && (phead->next != phead));
	Listnode* del = phead->next;
	phead->next = del->next;
	del->next->prev = phead;
	free(del);
	del = NULL;

}

Listnode* LTFind(Listnode* phead, ListData x)
{
	assert(phead);
	Listnode* f = phead->next;
	while (phead != f)
	{
		if (f->x == x)
		{
			return f;
		}
		f = f->next;
	}
	return NULL;
}

void LTInsert(Listnode* pos, ListData x)
{
	assert(pos);
	Listnode* newnode = LTcreatone(x);
	newnode->next = pos->next;
	newnode->prev = pos;
	pos->next->prev = newnode;
	pos->next = newnode;
}


void LTErase(Listnode* pos)
{
	assert(pos && (pos != pos->next));
	assert(pos->next->x != -1);
	Listnode* del = pos->next;
	del->next->prev = pos;
	pos->next = del->next;
	free(del);
	del = NULL;
}

void LTDestroy(Listnode* phead)
{
	assert(phead);
	Listnode* fel = phead->next;
	while (fel != phead)
	{
		fel->next->prev = fel->prev;
		fel->prev->next = fel->next;
		free(fel);
		fel = phead->next;
	}
	free(phead);
}
